
import os
import numpy as np
import sys
sys.path.append('.')

timestamp = '1580562342'
sign = 'train_time'
#sign = 'val_time'
# root = 'C:/Users/wanglinhui/Desktop/收拾旧山河/runs/{}'.format(timestamp)
root = '/home/code/BugTriageV2/runs/{}'.format(timestamp)
cost_matrix_name = "2-cost_matrix_{}.txt".format(sign)


def read_origin_confusion_matrix():
	confusions = []
	with open(os.path.join(root, 'confusion_matrix_{}.txt'.format(sign)), 'r') as reader:
		for line in reader.readlines():
			temp = line.strip()
			temp = list(map(int, temp.split('\t')))
			confusions.append(temp)
	# 行为真实标签，列为预测类别
	return confusions

def deal_cost_matrix(confusions):
	'''
		
	'''
	n_samples = np.sum(confusions)
	n_labels = len(confusions)
	print(n_samples)
	# print(confusions/n_samples)
	# 此时，行为真实标签，列为预测类别
	cost = confusions / n_samples
	cost = 1 - cost
	for i in range(len(cost)):
		for j in range(len(cost[i])):
			if cost[i][j] == 1:
				cost[i][j] = 1/n_samples
	cost = np.multiply(cost, 1-np.eye(n_labels, n_labels))
	cost = cost.T
	return cost

def deal_cost_matrix_2(confusions):
	'''
		
	'''
	n_samples = np.sum(confusions)
	n_category_samples = np.sum(confusions,axis=1)
	n_labels = len(confusions)
	print(n_samples)
	# print(confusions/n_samples)
	# 此时，行为真实标签，列为预测类别
	cost = confusions / n_samples
	cost = 1 - cost
	for i in range(len(cost)):
		for j in range(len(cost[i])):
			if cost[i][j] == 1:
				cost[i][j] = 1/n_samples
		if n_category_samples[i] != 0:
			cost[i] = cost[i] / n_category_samples[i]
	cost = np.multiply(cost, 1-np.eye(n_labels, n_labels))
	cost = cost.T
	return cost
def save_cost_matrix(cost):
	with open(os.path.join(root, cost_matrix_name), 'w') as writer:
		for i in range(len(cost)):
			writer.write('{}\n'.format('\t'.join(list(map(str, cost[i])))))


if __name__ == "__main__":
	confusions = read_origin_confusion_matrix()
	#cost = deal_cost_matrix(confusions)
	cost = deal_cost_matrix_2(confusions)
	save_cost_matrix(cost)
